package com.yzh.openai.domain.order.service;

import com.yzh.openai.domain.order.model.entity.*;
import com.yzh.openai.domain.order.model.valobj.PayStatusVO;
import com.yzh.openai.domain.order.repositoy.IOrderRepository;
import com.yzh.openai.types.common.Constants;
import com.yzh.openai.types.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.math.BigDecimal;

@Slf4j
public abstract class AbstractOrderService implements IOrderService {
    @Resource
    protected IOrderRepository orderRepository;

    @Override
    public PayOrderEntity createOrder(ShopCartEntity shopCartEntity) {
        try {
            //1.基础信息
            String openid = shopCartEntity.getOpenid();
            Integer productId = shopCartEntity.getProductId();

            //2.查询有效的未支付订单，如果存在直接返回微信支付 Native CodeUrl
            UnpaidOrderEntity unpaidOrderEntity = orderRepository.queryUnpaidOrder(shopCartEntity);
            if (unpaidOrderEntity != null && PayStatusVO.WAIT.equals(unpaidOrderEntity.getPayStatus()) && null != unpaidOrderEntity.getPayUrl()) {
                log.info("创建订单-已存在订单，已存在支付单，待支付。openid：{} orderId：{} payUrl：{}", openid, unpaidOrderEntity.getOrderId(), unpaidOrderEntity.getPayUrl());
                return PayOrderEntity.builder()
                        .openid(openid)
                        .orderId(unpaidOrderEntity.getOrderId())
                        .payUrl(unpaidOrderEntity.getPayUrl())
                        .payStatus(unpaidOrderEntity.getPayStatus())
                        .build();
            } else if (null != unpaidOrderEntity && null == unpaidOrderEntity.getPayUrl()) {
                log.info("创建订单-已存在订单，未存在支付单，正在创建... openid：{} orderId：{}", openid, unpaidOrderEntity.getOrderId());
                PayOrderEntity payOrderEntity = this.doPrepayOrder(openid, unpaidOrderEntity.getOrderId(), unpaidOrderEntity.getProductName(), unpaidOrderEntity.getTotalAmount());
                log.info("创建支付单-完成，生成支付单。openid：{} orderId：{} payUrl：{}", openid, payOrderEntity.getOrderId(), payOrderEntity.getPayUrl());
                return payOrderEntity;
            }

            //3.商品查询
            ProductEntity productEntity = orderRepository.queryProduct(productId);
            if (!productEntity.isAvailable()) {
                throw new BusinessException(Constants.ResponseCode.ORDER_PRODUCT_ERR, Constants.ResponseCode.ORDER_PRODUCT_ERR.getInfo());
            }

            //4.保存订单
            OrderEntity orderEntity = this.saveOrder(openid, productEntity);

            //5.创建支付
            PayOrderEntity payOrderEntity = this.doPrepayOrder(openid, orderEntity.getOrderId(), productEntity.getProductName(), orderEntity.getTotalAmount());
            log.info("创建订单-完成，已生成支付单。openid：{} orderId：{} payUrl：{}", openid, payOrderEntity.getOrderId(), payOrderEntity.getPayUrl());

            return payOrderEntity;
        } catch (BusinessException e) { 
            log.error("创建订单-异常。 openid: {} productId: {}", shopCartEntity.getOpenid(), shopCartEntity.getProductId(), e);
            throw new BusinessException(Constants.ResponseCode.UN_ERROR, Constants.ResponseCode.UN_ERROR.getInfo());
        }
    }

    /**
     * 生成预付款订单信息
     * @param openid        用户id
     * @param orderId       订单号
     * @param productName   商品名
     * @param amountTotal   订单金额
     * @return
     */
    protected abstract PayOrderEntity doPrepayOrder(String openid, String orderId, String productName, BigDecimal amountTotal);
    
    protected abstract OrderEntity saveOrder(String openid, ProductEntity productEntity);
}
